package tyk.Druid;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/***
 *@title BaseDao
 *@description <TODO description class purpose>
 *@author Tang'ya'kang
 *@VERSION 1.0.0
 *@CREATE 2023/5/5 15:55
 **/
public class BaseDao {
    private static DruidDataSource dataSource;
    private static ThreadLocal threadLocal;
    static{
        threadLocal=new ThreadLocal();
        dataSource=new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/javaweb");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    }
    public static int executeUpdate(String sql,Object ... par) throws SQLException {
        Connection connection=null;
        connection= (Connection) threadLocal.get();
        if(connection==null) {
            connection=dataSource.getConnection();
            threadLocal.set(connection);
        }
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        for(int i=1;i<=par.length;++i) preparedStatement.setObject(i,par[i-1]);
        int rows=preparedStatement.executeUpdate();
        if(connection.getAutoCommit()) connection.close();
        return rows;
    }

}
